package cat.joronya.supermanager.service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import cat.joronya.supermanager.Supermanager;

public class PrivateLeaguesJoinSync extends Object
{
	private static final String TAG = "supermanager";
	
	// service pel contexte
	private SupermanagerService service;
	
	// el client http on fer les peticions
	private DefaultHttpClient client = null;
	
	// status de retorn
	public int status = -1;
	
	private final String JOIN_URL = "http://supermanager.acb.com/inscribir.php";
	
	public PrivateLeaguesJoinSync(SupermanagerService service, DefaultHttpClient client)
	{
		this.service = service;
		this.client = client;
	}
	
	protected void join(String idpri, String ideqs, String clave) 
	{
		try
		{
			// checkejem per connectivitat
			ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();
			
			if( !online )
				throw new ConnectivityException();
			
			// POST: checkejar password i limits
			HttpPost preJoinPost = new HttpPost(JOIN_URL);
			
			List <NameValuePair> prenvps = new ArrayList <NameValuePair>();
			prenvps.add(new BasicNameValuePair("id_pri", idpri));
			prenvps.add(new BasicNameValuePair("clave", clave));
			prenvps.add(new BasicNameValuePair("control", "1"));
			prenvps.add(new BasicNameValuePair("x", "0"));
			prenvps.add(new BasicNameValuePair("y", "0"));
			
			preJoinPost.setEntity(new UrlEncodedFormEntity(prenvps, HTTP.ISO_8859_1));
			
			HttpResponse preResponse = client.execute(preJoinPost);
			ByteArrayOutputStream preOs = new ByteArrayOutputStream();
			preResponse.getEntity().writeTo(preOs);
	        String prePage = preOs.toString(HTTP.ISO_8859_1);
	        
	        // provem estat lliga: password i limits (salta exception)
	        PrivateLeagueJoinParser privateLeagueJoinParser = new PrivateLeagueJoinParser();
	        privateLeagueJoinParser.parse(prePage);
	        
			// POST: inscribir a lliga
			HttpPost httpPost = new HttpPost(JOIN_URL);
			
			String[] equips = ideqs.split(",");
			
	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	        nvps.add(new BasicNameValuePair("id_pri", idpri));
	        nvps.add(new BasicNameValuePair("numeq", ""+equips.length));
	        for(int i=0;i<equips.length;i++)
	        {
	        	nvps.add(new BasicNameValuePair("eq"+i, equips[i]));
	        }
	        nvps.add(new BasicNameValuePair("control", "2"));
	        nvps.add(new BasicNameValuePair("x", "0"));
	        nvps.add(new BasicNameValuePair("y", "0"));
	        
	        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
	        
	        HttpResponse response = client.execute(httpPost);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
	        response.getEntity().writeTo(os);
	        String searchPage = os.toString(HTTP.ISO_8859_1);
	        
	        // sempre donem per ok...
			
			// parsejat ok
	        status = Supermanager.PRIVATE_LEAGUE_JOIN_OK;
	        Log.d(TAG, "PrivateLeaguesJoinSync status: PRIVATE_LEAGUE_JOIN_OK - "+status);
	        return;
		}
		catch(PrivateLeagueWrongPasswordException wpe)
		{
			// error de password de lliga
			status = Supermanager.PRIVATE_LEAGUE_WRONG_PASSWORD;
			Log.d(TAG, "PrivateLeaguesJoinSync status: PRIVATE_LEAGUE_WRONG_PASSWORD - "+status);
			return;
		}
		catch(MaximumTeamsReachedException mtre)
		{
			// error lliga plena
			status = Supermanager.PRIVATE_LEAGUE_MAX_TEAM_REACHED;
			Log.d(TAG, "PrivateLeaguesJoinSync status: PRIVATE_LEAGUE_MAX_TEAM_REACHED - "+status);
			return;
		}
		catch(MaximumTeamsPerPlayerReachedException mtrppe)
		{
			// error lliga plena
			status = Supermanager.PRIVATE_LEAGUE_MAX_TEAM_PER_PLAYER_REACHED;
			Log.d(TAG, "PrivateLeaguesJoinSync status: PRIVATE_LEAGUE_MAX_TEAM_PER_PLAYER_REACHED - "+status);
			return;
		}
		catch(ConnectivityException ce){
			// error de connectivitat
			status = Supermanager.CONNECTIVITY_ERROR_STATUS;
	        Log.d(TAG, "PrivateLeaguesJoinSync status: CONNECTIVITY_ERROR_STATUS - "+status);
			return;
		}
		catch(Exception e){
			// altre error, notifiquem i anem offline
			status = Supermanager.OTHER_ERROR_STATUS;
	        Log.d(TAG, "PrivateLeaguesJoinSync status: OTHER_ERROR_STATUS - "+status);
			return;
		}
	}
}
